﻿Imports System.ComponentModel
Imports System.Data.SqlTypes


''' <summary>
''' ToRefactor : Stuff should go in MetaDataTable.... aleblanc - 2012-01-23
''' </summary>
''' <remarks></remarks>
Public Class GridExtSP
    Implements ISaveCommand, IReloadCommand

    'Not use Declare Private because of the Interface ISaveCommand
    Private Property DataSet As DataSet Implements ISaveCommand.Dataset

    Private Property VEdit As VEdit

    Public Delegate Function SaveCommandDelegate(ByVal aMetaDataTable As MetaDataTable) As Boolean
    Public SaveCMD As SaveCommandDelegate

    Public WithEvents MetaDataTable As CommonExt.MetaDataTable


    Public Event DeleteRow(ByVal row As DataRow, ByVal e As CancelEventArgs)
    Public Event AfterLoad(ByVal sender As Object, ByVal e As System.EventArgs)

    Private timeEdit As RepositoryItemTimeEdit
    Private formatType As DevExpress.Utils.FormatType

    Public editorView As DataView
    Public AllowCreate As Boolean
    Public AllowRead As Boolean
    Public AllowUpdate As Boolean
    Public AllowDelete As Boolean

    Public Property FormName As String Implements IReloadCommand.CtrlName
    Public Property SecureGrid() As Boolean = False

    Public Property GridActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property DefaultActionOptionList() As CommonExt.Base.ActionOptionList
    Public Property GridContextMenu() As GridViewMenu
    Public Property QueryName() As String

    Public Sub New(ByVal queryname As String)
        Me.New()
        Me.QueryName = queryname
    End Sub

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        GridControl1.ForceInitialize()
        AddHandler GridControl1.EmbeddedNavigator.ButtonClick, AddressOf GridControl1_EmbeddedNavigator_ButtonClick
        '
        AllowCreate = True
        AllowRead = True
        AllowUpdate = True
        AllowDelete = True
        '
        timeEdit = New RepositoryItemTimeEdit()
        Me.GridControl1.RepositoryItems.Add(timeEdit)
        InitActionOption()
        'typeMap = New Dictionary(Of SqlDbType, Type)
        'typeMap.Add(SqlDbType.BigInt, GetType(System.Int64))
    End Sub
    ''' <summary>
    ''' Shortcut key to:
    ''' CTRL-ALT-E = Export the Metaquery of the focus View
    ''' CTRL-ALT-Q = Display MetaQuery
    ''' CTRL-ALT-S = AutoSize the focus View
    ''' CTRL-ALT-L = SaveLayout of the focus View
    ''' CTRL-ALT-G = GetLayout of the focus View
    ''' CTRL-ALT-A = Display Allow... and optionbehevior 
    ''' CTRL-S = Save Change
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks>GridControl Always Raise whatever the view or mode we are (View vs Editing)</remarks>
    Private Sub GridControl1_ProcessGridKey(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles GridControl1.ProcessGridKey
        Dim message As String
        Dim view As GridView = DirectCast(GridControl1.FocusedView, GridView)
        '
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.Q Then
            message = String.Concat("MetaQuery: ", view.Tag.ToString, vbCrLf)
            MessageWindow.ShowMessage(message, MsgBoxStyle.Information)
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If

        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.A AndAlso view.Tag IsNot Nothing Then
            Dim ListString As Generic.List(Of String) = New List(Of String)
            ListString.Add(String.Format("AllowCreate : {0} ,{1}", Me.AllowCreate, vbCrLf))
            ListString.Add(String.Format("AllowRead : {0} ,{1}", Me.AllowRead, vbCrLf))
            ListString.Add(String.Format("AllowUpdate : {0} ,{1}", Me.AllowUpdate, vbCrLf))
            ListString.Add(String.Format("AllowDelete : {0} ,{1}", Me.AllowDelete, vbCrLf))
            ListString.Add(String.Format("Readonly : {0} ,{1}", Me.GridView1.OptionsBehavior.ReadOnly, vbCrLf))
            For Each acolumn As GridColumn In Me.GridView1.Columns
                ListString.Add(String.Format("column : {0} , ReadOnly : {1}, {2}", acolumn.Name, acolumn.OptionsColumn.ReadOnly, vbCrLf))
            Next
            message = ""
            For Each astring In ListString
                message = String.Concat(message, astring)
            Next
            MessageWindow.ShowMessage(message, MsgBoxStyle.Information)
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If




        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.S Then
            view.BestFitColumns()
            e.Handled = True
        ElseIf e.Control AndAlso e.KeyCode = Keys.S Then
            Me.SaveCommand()
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If

        'Export MetaCommand
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.E Then
            Using mq As MetaQuery = MetaQuery.GetMetaQueryByName(view.Tag.ToString)
                Using aFile As New System.Windows.Forms.SaveFileDialog
                    aFile.DefaultExt = "xml"
                    aFile.FileName = String.Format("MetaQuery_{0}", mq.QueryName)
                    aFile.AutoUpgradeEnabled = True
                    If aFile.ShowDialog() = DialogResult.OK Then
                        If SystemBoxSDK.PL.MetaSDK.MetaCommand_PL.ExportMetaCommand(aFile.FileName, mq.QueryID) Then
                            MessageWindow.ShowMessage("Export Command Successful", MsgBoxStyle.Information)
                        End If
                    End If
                End Using
            End Using
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If

        'Save Layout of the Focus View
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.L Then
            Using aFile As New System.Windows.Forms.SaveFileDialog
                aFile.DefaultExt = "xml"
                aFile.FileName = "GridExtLayout_" + view.Tag.ToString
                aFile.AutoUpgradeEnabled = True
                If aFile.ShowDialog() = DialogResult.OK Then
                    view.SaveLayoutToXml(aFile.FileName)
                    MessageWindow.ShowMessage("Save Layout Successful", MsgBoxStyle.Information)
                End If
            End Using
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If

        'Load Layout For the Focus View
        If e.Control AndAlso e.Alt AndAlso e.KeyCode = Keys.G Then
            Using aFile As New System.Windows.Forms.OpenFileDialog
                aFile.DefaultExt = "xml"
                aFile.FileName = String.Format("GridExtLayout_{0}.xml", view.Tag)
                aFile.AutoUpgradeEnabled = True
                If aFile.ShowDialog() = DialogResult.OK Then
                    view.RestoreLayoutFromXml(aFile.FileName)
                End If
            End Using
            e.Handled = True 'TestPoint: Si on le met pas on peut passer 2 ou 3 fois selon le nombre de touche. aleblanc
        End If
    End Sub

    Public Function SaveCommand() As Boolean Implements CommonExt.ISaveCommand.SaveCommand
        'OutstandingIssue
        Try
            Me.Cursor = Cursors.WaitCursor
            'On force la fermeture de l'éditeur.
            GridControl1.FocusedView.CloseEditor()
            GridControl1.FocusedView.UpdateCurrentRow()
            If SaveCMD IsNot Nothing Then
                SaveCMD(Me.MetaDataTable)
            End If

        Catch ex As Exception
            MessageWindow.ShowMessage(ex, MsgBoxStyle.Information)
        Finally
            Me.Cursor = Cursors.Default
        End Try
        Return True
    End Function

    'Basé sur l'exemple de http://www.devexpress.com/Support/Center/e/E1127.aspx
    Private Sub GridControl1_EmbeddedNavigator_ButtonClick(ByVal sender As Object, ByVal e As NavigatorButtonClickEventArgs)
        If e.Button.ButtonType = NavigatorButtonType.Remove Then
            DeleteCurrentRows()
            'TestPoint: Si on enleve cette ligne ca continue l'événement et va delete l'autre ligne en focus (2 lignes) - aleblanc 2011-10-07.
            e.Handled = True
        End If
    End Sub

#Region " Context Action Menu"
    Private Sub InitActionOption()
        Dim act As CommonExt.Base.ActionOption
        GridActionOptionList = New CommonExt.Base.ActionOptionList()
        DefaultActionOptionList = New CommonExt.Base.ActionOptionList()

        act = New CommonExt.Base.ActionOption("GridOption", "Refresh", "Refresh Data", AddressOf ContextMenuReloadGrid, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("GridOption", "ToExcel", "Export to Excel", AddressOf ContextMenuExportToExcel, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("GridOption", "VEdit", "VEdit (From MainView Only)", AddressOf ContextMenuVEdit, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOption", "SaveData", "Save", AddressOf ContextMenuSave, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOption", "DeleteData", "Delete", AddressOf ContextMenuDelete, True, True)
        DefaultActionOptionList.Add(act)

        act = New CommonExt.Base.ActionOption("DefaultOptionZ", "ZoomIn", "Zoom In", AddressOf ContextMenuZoomIn, False, True)
        DefaultActionOptionList.Add(act)
        act = New CommonExt.Base.ActionOption("DefaultOptionZ", "ZoomOut", "Zoom Out", AddressOf ContextMenuZoomOut, False, True)
        DefaultActionOptionList.Add(act)
    End Sub
    Private Sub ContextMenuSave(ByVal sender As System.Object, ByVal e As EventArgs)
        Me.SaveCommand()
    End Sub
    Private Sub ContextMenuDelete(ByVal sender As System.Object, ByVal e As EventArgs)
        DeleteCurrentRows()
    End Sub
    Private Sub DeleteCurrentRows()
        Dim view As GridView = CType(Me.GridControl1.FocusedView, GridView)
        If DeleteRowEvent Is Nothing Then
            view.DeleteSelectedRows()
        Else
            Dim cnclEvent As New CancelEventArgs(False)
            RaiseEvent DeleteRow(view.GetFocusedDataRow, cnclEvent)
            If Not cnclEvent.Cancel Then
                view.DeleteSelectedRows()
            End If
        End If
    End Sub
    Private Sub ContextMenuVEdit(ByVal sender As System.Object, ByVal e As EventArgs)

        'Dim detailview As GridView = CType(Me.GridControl1.FocusedView, GridView)
        'Dim detailTable As MetaDataTable = CType(_aDataset.Tables(detailview.Tag.ToString), MetaDataTable)
        '_aVEdit = New VEdit
        '_aVEdit.Init(detailTable, detailview)
        ''HOWto: get the datatable rowindex from a Grid Devex

        'OutStandingIssue: Marche pas sur les child. Ne se positionne pas sur le bon record... aleblanc 2011-07-29

        '_aVEdit.ShowVEdit(detailview.GetDataSourceRowIndex(detailview.FocusedRowHandle))


        If VEdit Is Nothing Then
            VEdit = New VEdit
            VEdit.Init(MetaDataTable, CType(GridControl1.MainView, GridView))
        End If
        'HOWto: get the datatable rowindex from a Grid Devex
        VEdit.ShowVEdit(GridView1.GetDataSourceRowIndex(GridView1.FocusedRowHandle))
    End Sub
    Private Sub ContextMenuExportToExcel(ByVal sender As System.Object, ByVal e As EventArgs)
        'OutStandingIssue: On ne peut pas exporter la vue detail seulement... Il faut passerpar la Vue principal.
        'Work Around: Reconstruire une grille avec la table dataSet via le FocusedView.Tag.ToString (Comme ContextMenuVEdit) et appliquer un filtre apartir du la Row Parent.
        'aleblanc - 2011-07-26
        'http://www.devexpress.com/Support/Center/p/S130097.aspx.  C'est pareil pour les XLS
        '
        Dim filename As String
        Try
            'filename = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), GridView1.Tag.ToString + ".xls")
            filename = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), GridView1.Tag.ToString)
            Using aFile As New System.Windows.Forms.SaveFileDialog
                aFile.DefaultExt = "xls"
                aFile.FileName = filename
                aFile.AutoUpgradeEnabled = True
                If aFile.ShowDialog() = DialogResult.OK Then

                    GridView1.OptionsPrint.AutoWidth = False
                    GridView1.OptionsPrint.PrintDetails = True
                    GridView1.OptionsPrint.ExpandAllDetails = True
                    GridView1.OptionsPrint.ExpandAllGroups = True
                    GridView1.ExportToXls(aFile.FileName)

                    MessageWindow.ShowMessage(String.Format("Export To Excel Succesfull.{0}{0}Your Filename is: {1}", vbCrLf, aFile.FileName), MsgBoxStyle.Information)

                End If
            End Using
        Catch ex As Exception
            Throw ex
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuReloadGrid(ByVal sender As System.Object, ByVal e As EventArgs)
        ReloadGrid()
    End Sub
#End Region
    Public Sub ReloadGrid()
        Me.Cursor = Cursors.WaitCursor
        GridControl1.DataSource = Nothing
        '
        'On enleve les LOV et les editeurs de la grilles
        'Car pour les LOV on réutilise les colonnes qui on déjà le même LOV
        GridControl1.RepositoryItems.Clear()

        InitGridExt()
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub ContextMenuZoomIn(ByVal sender As System.Object, ByVal e As EventArgs)
        GridControl1.FocusedView.ZoomView()
    End Sub
    Private Sub ContextMenuZoomOut(ByVal sender As System.Object, ByVal e As EventArgs)
        GridControl1.FocusedView.NormalView()
    End Sub
    'Private Sub _aview_MasterRowExpanded(sender As Object, e As DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs) Handles _aview.MasterRowExpanded
    '    Dim chldView As DevExpress.XtraGrid.Views.Grid.GridView = CType(GridControl1.FocusedView, DevExpress.XtraGrid.Views.Grid.GridView)
    '    Dim row As Integer = chldView.FocusedRowHandle

    '    _aview = CType(chldView.GetDetailView(row, e.RelationIndex), DevExpress.XtraGrid.Views.Grid.GridView)
    'End Sub
    Public Sub InitGridExt()
        Dim mainViewAccess As MetaQueryAccess = Nothing
        Dim mqCtrlName As String = Nothing

        MetaDataTable = New MetaDataTable()
        MetaDataTable.QueryName = QueryName
        MetaDataTable.GetMetaCommand()
        ' Pour le backgoudWorker - aleblanc - 2011-09-06
        'If Not bgWorker.IsBusy Then
        '    waitWindow = New DevExpress.Utils.WaitDialogForm("Un Instant svp", "Chargement des données...")
        '    waitWindow.LookAndFeel.SkinName = "Blue"
        '    waitWindow.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Skin
        '    waitWindow.LookAndFeel.UseDefaultLookAndFeel = False
        '    waitWindow.LookAndFeel.UseWindowsXPTheme = False
        '    bgWorker.RunWorkerAsync(withChild)
        'End If
        GridControl1.BeginUpdate()
        If Not String.IsNullOrWhiteSpace(FormName) Then
            Me.AllowRead = False
            Me.AllowUpdate = False
            Me.AllowDelete = False
            Me.AllowCreate = False
            If Not String.IsNullOrEmpty(QueryName) Then
                mqCtrlName = AppManager.GetControlMqFromForm(FormName, QueryName)
                If Not String.IsNullOrWhiteSpace(mqCtrlName) Then
                    mainViewAccess = New MetaQueryAccess(mqCtrlName)
                    If mainViewAccess IsNot Nothing Then
                        Me.AllowRead = CBool(mainViewAccess.AllowRead)
                        Me.AllowUpdate = mainViewAccess.AllowUpdate
                        Me.AllowDelete = mainViewAccess.AllowDelete
                        Me.AllowCreate = mainViewAccess.AllowCreate
                    End If
                End If
            End If
        End If
        If AllowRead Then
            GridControl1.LevelTree.Nodes.Clear()
            BuildTableFromMetaQuery()
            GridControl1.DataSource = MetaDataTable.DefaultView
            InitMainView()
        End If
        GridControl1.EndUpdate()
    End Sub

    Private Sub BuildTableFromMetaQuery()
        Dim sqlCmd As SqlCommand = Nothing
        Dim column As DataColumn = Nothing

        Dim mq As MetaQuery = MetaQuery.GetMetaQueryByName(QueryName)
        If mq IsNot Nothing Then
            sqlCmd = MetaQuery.GetSPCmdByMeta(mq, False)
            Me.MetaDataTable.Adapter.UpdateCommand = sqlCmd
            Me.MetaDataTable.Adapter.InsertCommand = sqlCmd
            If sqlCmd IsNot Nothing Then
                mq.FillMetaParams()
                'MetaDataTable.Columns.r()
                For Each row As DataRow In mq.MetaParams.Rows
                    'For Each param As SqlParameter In sqlCmd.Parameters
                    column = MetaDataTable.Columns.Add()
                    column.ColumnName = row("ColumnName").ToString
                    column.Caption = row("pCaption").ToString
                    column.SetOrdinal(CInt(row("pOrder")))
                    column.DataType = IdRepository.SqlDbTypeToType(sqlCmd.Parameters(column.ColumnName).SqlDbType)
                    'Next
                Next
            End If
        End If
    End Sub

    Private Sub InitMainView()
        Dim colVisible As Boolean
        Dim mainView As Views.Base.ColumnView = CType(GridControl1.MainView, Views.Base.ColumnView)
        Dim column As DevExpress.XtraGrid.Columns.GridColumn
        Dim tableColumns As DataTable
        Dim colname As String

        'This action is mandaotry due to the fact that as soon as Grid control datasource is set
        'the columns view are loaded but not specified the application requires
        mainView.Columns.Clear()

        ' On le force a false car quand on a des cellule de mergé le Row Selector disparait
        GridView1.OptionsView.AllowCellMerge = False
        '

        tableColumns = MetaDataTable.MetaParams
        '
        Me.MetaDataTable.DefaultView.AllowEdit = Me.AllowUpdate
        Me.MetaDataTable.DefaultView.AllowDelete = Me.AllowDelete
        Me.MetaDataTable.DefaultView.AllowNew = Me.AllowCreate
        '
        For Each row As DataRow In tableColumns.Rows
            colname = row("ColumnName").ToString
            colVisible = CBool(IIf(CInt(row("pVisible")) = 0, False, True))
            column = mainView.Columns.AddField(colname)
            'column.VisibleIndex = CInt(row("pOrder"))
            'column.Caption = row("pCaption").ToString
            column.Visible = colVisible
            column.Width = CInt(row("pWidth"))
            column.OptionsColumn.AllowEdit = Not CBool(row("pLocked"))
            column.ToolTip = row("pToolTip").ToString

            If Not String.IsNullOrEmpty(Trim(row("pBackColor").ToString)) Then
                column.AppearanceCell.BackColor = ColorTranslator.FromOle(Math.Abs(CInt(row("pBackColor"))))
            End If

            If CBool(row("pMerge")) Then
                GridView1.OptionsView.AllowCellMerge = True
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True
            Else
                column.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False
            End If

            If CInt(row("pGroupByOrder")) > 0 Then
                column.GroupIndex = CInt(row("pGroupByOrder"))
            End If
            '
            formatType = DevExGridHelper.GetFormatType(row)
            If formatType = DevExpress.Utils.FormatType.DateTime Then

                timeEdit.DisplayFormat.FormatType = formatType
                timeEdit.DisplayFormat.FormatString = row("pNumberFormat").ToString
                timeEdit.EditFormat.FormatType = formatType
                timeEdit.EditFormat.FormatString = row("pNumberFormat").ToString
                timeEdit.EditMask = row("pNumberFormat").ToString
                column.ColumnEdit = timeEdit
            End If
            '
            column.DisplayFormat.FormatType = formatType
            column.DisplayFormat.FormatString = row("pNumberFormat").ToString

            'If column.Caption = "Target" And column.RealColumnEdit IsNot Nothing Then
            '    column.RealColumnEdit.EditFormat.FormatType = formatType
            '    column.RealColumnEdit.EditFormat.FormatString = row("pNumberFormat").ToString
            'End If

            '
            'OutStandingIssue: pSummaryInfo la colonne est retourné de la SP reste a l'implenté - aleblanc - 2011-07-19
            'arow("pSummaryInfo")	
            'Column.SummaryItem.SummaryType = 
            'Column.SummaryItem.SummaryValue = 
            DevExGridHelper.AssignCustomSummaryProperties(GridView1, column, row)
        Next

        GridView1.GridControl = Me.GridControl1
        GridView1.Name = "ParentView"
        GridView1.Tag = MetaDataTable.TableName
        GridView1.HorzScrollVisibility = Views.Base.ScrollVisibility.Always
        '
        GridView1.OptionsDetail.AllowExpandEmptyDetails = True
        GridView1.OptionsDetail.EnableDetailToolTip = True
        '
        GridView1.OptionsFilter.DefaultFilterEditorView = FilterEditorViewMode.VisualAndText
        GridView1.OptionsFilter.ShowAllTableValuesInFilterPopup = True
        GridView1.OptionsFilter.UseNewCustomFilterDialog = True
        '
        If Me.AllowCreate Then
            GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Top
        Else
            GridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None
        End If
        '
        GridView1.OptionsView.ShowAutoFilterRow = True
        GridView1.OptionsView.ShowChildrenInGroupPanel = True
        GridView1.OptionsView.ShowFilterPanelMode = Views.Base.ShowFilterPanelMode.ShowAlways

        'Le nom de l'onglet de la vue
        'GridView1.OptionsView.ShowViewCaption = True   'Permet d'afficher le nom du Caption dans une ligne en haut du Grid
        GridView1.ViewCaption = MetaDataTable.MetaCommand.Caption
        'Make sure that the columns are define in the view before assignning LOV'S
        MetaDataTable.MetaCommand.GetParamsLOV_LKP()
        DevExGridHelper.AssignLKP(CType(mainView, GridView), MetaDataTable, Me.GridControl1)
        tableColumns.Dispose()
    End Sub

    Private Sub GridControl1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles GridControl1.MouseClick
        Dim point As Point
        Dim hi As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo

        If e.Button = MouseButtons.Right Then
            ' checking if the end-user has right clicked the grid control 
            point = New Point(e.X, e.Y)
            hi = CType(GridControl1.FocusedView.CalcHitInfo(point), Grid.ViewInfo.GridHitInfo)
            If hi.HitTest = Grid.ViewInfo.GridHitTest.RowIndicator Then
                DoShowMainViewMenu(hi)
            End If
        End If
    End Sub
    Sub DoShowMainViewMenu(ByVal hi As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo)
        Dim item As DXMenuItem
        Dim grpName As String = String.Empty

        GridContextMenu = New GridViewMenu(GridView1)
        If GridActionOptionList IsNot Nothing Then
            For Each action As CommonExt.Base.ActionOption In DefaultActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                item.Enabled = action.Enabled
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                GridContextMenu.Items.Add(item)
            Next
            'Add Action Option that need the grid DataRow
            For Each action As CommonExt.Base.ActionOption In Me.GridActionOptionList
                item = New DXMenuItem(action.OptionTitle, action.EventHandler, Nothing)
                item.Tag = GridView1.GetFocusedDataRow()
                item.Enabled = action.Enabled
                'item.Image = action.OptionIcon
                If item.Tag Is Nothing Then
                    item.Enabled = False
                End If
                'Add new Group Separator when Group Name change
                If (grpName <> action.OptionGroup And grpName <> String.Empty) Then
                    item.BeginGroup = True
                End If
                grpName = action.OptionGroup
                If String.IsNullOrEmpty(action.IndentLevelReference) OrElse action.IndentLevelReference = GridView1.Tag.ToString Then
                    GridContextMenu.Items.Add(item)
                End If
            Next
            'Display Menu
            GridContextMenu.Show(hi.HitPoint)
        End If
    End Sub
    Private Sub GridExtSP_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        InitGridExt()
        If AfterLoadEvent IsNot Nothing Then
            RaiseEvent AfterLoad(sender, e)
        End If
    End Sub

    Public Sub ReloadCommand() Implements CommonExt.IReloadCommand.ReloadCommand
        ReloadGrid()
    End Sub

    Private Sub GridView1_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles GridView1.RowStyle
        DevExGridHelper.AssignSearchAndAddRowProperty(e)
    End Sub
End Class
